<template>
  <view class="album-edit">
    <!-- 表单区域 -->
    <view class="form-section">
      <!-- 封面 -->
      <view class="cover-section">
        <view class="section-title">相册封面</view>
        <view class="cover-upload" @click="changeCover">
          <image 
            v-if="form.coverUrl" 
            :src="form.coverUrl" 
            mode="aspectFill" 
            class="cover-image"
          ></image>
          <!-- 上传状态指示器 -->
          <view class="upload-status" v-if="uploadStatus.success || uploadStatus.text === '上传失败，请重试'">
            <u-icon :name="uploadStatus.success ? 'checkmark-circle' : 'close-circle'" 
                    :color="uploadStatus.success ? '#3a8838' : '#ff5a5f'"
                    size="40">
            </u-icon>
          </view>
          <view v-else-if="!form.coverUrl" class="upload-placeholder">
            <u-icon name="camera" size="48" color="#999"></u-icon>
            <text>点击选择封面</text>
          </view>
          <!-- 加载中指示器 -->
          <view class="upload-loading" v-if="isUploading">
            <u-loading-icon size="36" color="#3a8838"></u-loading-icon>
            <text>上传中...</text>
          </view>
        </view>
      </view>

      <!-- 表单内容 -->
      <view class="form-content">
        <view class="form-item">
          <text class="label">相册名称</text>
          <input 
            type="text"
            v-model="form.title"
            placeholder="请输入相册名称"
            class="input"
            maxlength="20"
          />
          <text class="input-count">{{form.title.length}}/20</text>
        </view>

        <view class="form-item">
          <text class="label">相册描述</text>
          <textarea
            v-model="form.description"
            placeholder="请输入相册描述"
            class="textarea"
            maxlength="200"
          ></textarea>
          <text class="input-count textarea-count">{{form.description.length}}/200</text>
        </view>

        <view class="form-item">
          <text class="label">访问权限</text>
          <view class="privacy-switch">
            <text>私密相册</text>
            <switch 
              :checked="form.status === 0"
              @change="onPrivacyChange"
              color="#3a8838"
            />
          </view>
        </view>
      </view>

      <!-- 加载中状态 -->
      <view class="loading-state" v-if="isLoading">
        <view class="loading-spinner">
          <u-loading-icon size="36" color="#3a8838"></u-loading-icon>
        </view>
        <text>加载中...</text>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-buttons">
      <button class="btn cancel" @click="cancel">取消</button>
      <button class="btn save" :disabled="isUploading || !form.title.trim()" @click="save">{{ isUploading ? '上传中...' : '保存' }}</button>
    </view>
  </view>
</template>

<script>
import { getMyAlbums, updateAlbum } from '@/api/album'
import { uploadPhoto } from '@/api/photo'
import { getImageBlob } from '@/utils/image.js'

export default {
  data() {
    return {
      albumId: '',
      form: {
        title: '',
        description: '',
        status: 1,  // 0-私密，1-公开
        coverUrl: '',
        coverPhotoId: null
      },
      isLoading: false,
      isUploading: false,
      uploadStatus: {
        text: '',
        success: false
      }
    }
  },
  onLoad(options) {
    this.albumId = options.id;
    if (this.albumId) {
      this.loadAlbumInfo();
    }
  },
  methods: {
    // 加载相册信息
    async loadAlbumInfo() {
      this.isLoading = true;
      try {
        // 使用首页列表API获取相册信息而不是单独的详情API
        const result = await getMyAlbums();
        const albums = result.data?.records || [];
        
        // 从列表中找到当前相册
        const currentAlbum = albums.find(a => a.albumId.toString() === this.albumId.toString());
        
        if (currentAlbum) {
          this.form = {
            title: currentAlbum.title || '',
            description: currentAlbum.description || '',
            status: currentAlbum.status != null ? currentAlbum.status : 1,
            coverPhotoId: currentAlbum.coverPhotoId
          };
          
          // 加载封面图片
          if (currentAlbum.coverPhoto) {
            try {
              const coverUrl = await getImageBlob(currentAlbum.coverPhoto);
              this.form.coverUrl = coverUrl;
            } catch (err) {
              console.error('加载封面图片失败:', err);
            }
          } else if (currentAlbum.coverUrl) {
            this.form.coverUrl = currentAlbum.coverUrl;
          }
        } else {
          console.warn('在列表中未找到当前相册信息');
          uni.showToast({
            title: '未找到相册信息',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载相册信息失败:', error);
        uni.showToast({
          title: '加载相册信息失败',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
      }
    },
    
    // 更换封面
    changeCover() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          // 先显示预览
          this.form.coverUrl = res.tempFilePaths[0];
          this.uploadStatus = { text: '', success: false };
          
          // 立即上传
          try {
            await this.uploadCoverPhoto(res.tempFilePaths[0]);
          } catch (error) {
            console.error('上传封面失败:', error);
            uni.showToast({
              title: '封面上传失败',
              icon: 'none'
            });
          }
        }
      });
    },
    
    // 上传封面照片
    async uploadCoverPhoto(filePath) {
      this.isUploading = true;
      
      try {
        // 准备上传数据 - 不再关联到具体相册
        const uploadData = {
          file: filePath,
          title: this.form.title ? (this.form.title + '的封面') : '相册封面',
          status: this.form.status
          // 移除 albumId 字段，使照片不属于任何相册
        };
        
        // 调用上传API
        const result = await uploadPhoto(uploadData);
        
        // 保存返回的照片ID
        if (result.data) {
          this.form.coverPhotoId = result.data;
          this.uploadStatus.text = '上传成功';
          this.uploadStatus.success = true;
        } else {
          throw new Error('未返回有效的照片ID');
        }
      } catch (error) {
        console.error('上传封面失败:', error);
        this.uploadStatus.text = '上传失败，请重试';
        this.uploadStatus.success = false;
        
        uni.showToast({
          title: '封面上传失败',
          icon: 'none'
        });
      } finally {
        this.isUploading = false;
      }
    },
    
    // 切换私密状态
    onPrivacyChange(e) {
      this.form.status = e.detail.value ? 0 : 1;
    },
    
    // 取消编辑
    cancel() {
      uni.navigateBack();
    },
    
    // 保存修改
    async save() {
      if (!this.form.title.trim()) {
        uni.showToast({
          title: '请输入相册名称',
          icon: 'none'
        });
        return;
      }
      
      try {
        // 准备更新数据
        const updateData = {
          title: this.form.title,
          description: this.form.description,
          status: this.form.status
        };
        
        // 如果有封面照片ID，一并更新
        if (this.form.coverPhotoId) {
          updateData.coverPhotoId = this.form.coverPhotoId;
        }
        
        await updateAlbum(this.albumId, updateData);
        
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        });
        
        // 通知相册详情页刷新
        uni.$emit('album:updated', { albumId: this.albumId });
        
        setTimeout(() => {
          uni.navigateBack({
            success: () => {
              // 再次发送事件确保刷新
              uni.$emit('album:updated', { albumId: this.albumId });
            }
          });
        }, 1500);
      } catch (error) {
        console.error('保存失败:', error);
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style>
.album-edit {
  min-height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
}

.form-section {
  flex: 1;
  padding-bottom: 30rpx;
}

.cover-section {
  background-color: #fff;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 28rpx;
  color: #666;
  padding: 30rpx;
}

.cover-upload {
  margin: 0 30rpx 30rpx;
  height: 400rpx;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  overflow: hidden;
  position: relative;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
}

.upload-placeholder text {
  font-size: 26rpx;
  color: #999;
}

.upload-status {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  z-index: 10;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  padding: 6rpx;
}

.upload-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
}

.upload-loading text {
  margin-top: 20rpx;
  font-size: 28rpx;
}

.form-content {
  background-color: #fff;
  padding: 0;
  margin-bottom: 20rpx;
}

.form-item {
  margin-bottom: 0;
  padding: 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
  position: relative;
}

.form-item:last-child {
  border-bottom: none;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 15rpx;
}

.input {
  width: 100%;
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
}

.textarea {
  width: 100%;
  height: 200rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
}

.input-count {
  position: absolute;
  right: 30rpx;
  bottom: 30rpx;
  font-size: 24rpx;
  color: #999;
}

.textarea-count {
  bottom: 50rpx;
}

.privacy-switch {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: transparent;
  padding: 0;
}

.privacy-switch text {
  font-size: 28rpx;
  color: #333;
}

.bottom-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  z-index: 100;
}

.btn {
  width: 45%;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.cancel {
  background-color: #f5f5f5;
  color: #666;
}

.save {
  background-color: #3a8838;
  color: #fff;
}

.save[disabled] {
  background-color: #cccccc;
  color: #ffffff;
  opacity: 0.8;
}

.loading-state {
  padding: 100rpx 0;
  text-align: center;
  color: #999;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  display: flex;
  justify-content: center;
  margin-bottom: 20rpx;
}
</style> 